import { createElement } from 'react'
import { RouteConfig, MenuItemConfig } from './types'

/**
 * 根据路由配置生成菜单配置
 */
export const generateMenuItems = (routes: RouteConfig[]): MenuItemConfig[] => {
  return routes
    .filter(route => route.showInMenu)
    .map(route => ({
      key: route.path,
      icon: route.icon ? createElement(route.icon) : undefined,
      label: route.name,
      ...(route.children && route.children.length > 0 
        ? { children: generateMenuItems(route.children) }
        : {}
      ),
    })) as MenuItemConfig[]
}

/**
 * 根据路径查找路由配置
 */
export const findRouteByPath = (routes: RouteConfig[], path: string): RouteConfig | undefined => {
  if (!routes || !Array.isArray(routes)) {
    return undefined
  }
  
  for (const route of routes) {
    if (route.path === path) {
      return route
    }
    if (route.children) {
      const childRoute = findRouteByPath(route.children, path)
      if (childRoute) {
        return childRoute
      }
    }
  }
  return undefined
}

/**
 * 获取面包屑导航
 */
export const getBreadcrumbs = (routes: RouteConfig[], path: string): RouteConfig[] => {
  const breadcrumbs: RouteConfig[] = []
  
  const findBreadcrumbs = (routeList: RouteConfig[], targetPath: string, currentPath: RouteConfig[] = []): boolean => {
    for (const route of routeList) {
      const newPath = [...currentPath, route]
      
      if (route.path === targetPath) {
        breadcrumbs.push(...newPath)
        return true
      }
      
      if (route.children && findBreadcrumbs(route.children, targetPath, newPath)) {
        return true
      }
    }
    return false
  }
  
  findBreadcrumbs(routes, path)
  return breadcrumbs
}

/**
 * 检查路径是否为有效路由
 */
export const isValidRoute = (routes: RouteConfig[], path: string): boolean => {
  if (!routes || !Array.isArray(routes)) {
    return false
  }
  
  const route = findRouteByPath(routes, path)
  return route !== undefined && !route.meta?.is404
}

/**
 * 获取所有有效的路径列表
 */
export const getAllValidPaths = (routes: RouteConfig[]): string[] => {
  const paths: string[] = []
  
  const collectPaths = (routeList: RouteConfig[]) => {
    routeList.forEach(route => {
      // 只收集有组件且不是404页面且不是重定向路由的路径
      if (route.component && !route.meta?.is404 && !route.meta?.redirect) {
        paths.push(route.path)
      }
      if (route.children) {
        collectPaths(route.children)
      }
    })
  }
  
  collectPaths(routes)
  return paths
}

/**
 * 检查路径是否需要认证
 */
export const requiresAuth = (routes: RouteConfig[], path: string): boolean => {
  const route = findRouteByPath(routes, path)
  return route?.requireAuth ?? true // 默认需要认证
}